<?php

// PHP雪里开轻量级报修系统 V1.0Beta
// 演示地址: http://baoxiu.chalide.cn
// 更新关注: /weivote
// 文件路径: sys/repa.php
// 文件大小: 23862 字节
// 最后修改时间: 2025-05-21 16:33:58
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权

/**
 * 本文件功能：系统管理员查看报修详情
 * 版权声明：保留发行权和署名权
 * 作者信息：功能反馈:15058593138@qq.com(手机号同微信)
 */

// 获取报修ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    echo '<div class="alert alert-danger">无效的报修ID</div>';
    echo '<p><a href="?do=libx" class="btn btn-primary">返回列表</a></p>';
    return;
}

// 处理AJAX请求
if (isset($_GET['act'])) {
    switch ($_GET['act']) {
        case 'reply':
            // 添加回复
            $content = isset($_POST['content']) ? trim($_POST['content']) : '';
            $status = isset($_POST['status']) ? trim($_POST['status']) : '';
            $images_json = isset($_POST['images_json']) ? trim($_POST['images_json']) : '';
            
            if (empty($content) && empty($images_json)) {
                json_error('请输入回复内容或上传图片');
            }
            
            if (!in_array($status, ['未处理', '处理中', '已完成', '已关闭'])) {
                json_error('无效的状态');
            }
            
            // 解析图片JSON
            $images = !empty($images_json) ? json_decode($images_json, true) : [];
            
            // 准备沟通记录数据
            $hist_data = [
                'bxiu_id' => $id,
                'user_id' => $_SESSION['user_id'],
                'content' => $content,
                'images' => !empty($images) ? json_encode($images, JSON_UNESCAPED_UNICODE) : null,
                'create_time' => date('Y-m-d H:i:s')
            ];
            
            // 开始事务
            $db->beginTransaction();
            
            try {
                // 插入沟通记录
                $hist_result = $db->insert('hist', $hist_data);
                
                if (!$hist_result) {
                    throw new Exception('回复失败: ' . $mysqli->error);
                }
                
                // 更新主表状态和时间
                $bxiu_data = [
                    'status' => $status,
                    'update_time' => date('Y-m-d H:i:s')
                ];
                
                $bxiu_result = $db->update('bxiu', $bxiu_data, "id = {$id}");
                
                if (!$bxiu_result) {
                    throw new Exception('更新状态失败: ' . $mysqli->error);
                }
                
                // 提交事务
                $db->commit();
                
                json_success('处理成功');
            } catch (Exception $e) {
                // 回滚事务
                $db->rollback();
                
                json_error($e->getMessage());
            }
            break;
            
        case 'delete_image':
            // 删除图片
            $image_path = isset($_POST['path']) ? trim($_POST['path']) : '';
            $record_type = isset($_POST['type']) ? trim($_POST['type']) : '';
            $record_id = isset($_POST['record_id']) ? intval($_POST['record_id']) : 0;
            
            if (empty($image_path)) {
                json_error('图片路径不能为空');
            }
            
            if (!in_array($record_type, ['bxiu', 'hist']) || $record_id <= 0) {
                json_error('无效的记录类型或ID');
            }
            
            // 获取记录
            $record = $db->getOne($record_type, "id = {$record_id}");
            if (!$record) {
                json_error('记录不存在');
            }
            
            // 解析图片JSON
            $images = !empty($record['images']) ? json_decode($record['images'], true) : [];
            
            // 从图片数组中移除指定图片
            $index = array_search($image_path, $images);
            if ($index !== false) {
                array_splice($images, $index, 1);
                
                // 更新记录
                $data = [
                    'images' => !empty($images) ? json_encode($images, JSON_UNESCAPED_UNICODE) : null
                ];
                
                $result = $db->update($record_type, $data, "id = {$record_id}");
                
                if ($result) {
                    // 尝试删除物理文件（但不影响操作结果）
                    @unlink($image_path);
                    
                    json_success('图片删除成功');
                } else {
                    json_error('图片删除失败: ' . $mysqli->error);
                }
            } else {
                json_error('图片不存在于记录中');
            }
            break;
    }
    exit;
}

// 包含头部
include './inc/head.php';

// 获取报修详情
$repair = $db->getOne('bxiu', "id = {$id}");

if (!$repair) {
    echo '<div class="alert alert-danger">报修记录不存在</div>';
    echo '<p><a href="?do=libx" class="btn btn-primary">返回列表</a></p>';
    return;
}

// 获取提交用户信息
$submitter = $db->getOne('stux', "id = {$repair['user_id']}");

// 获取沟通记录
$history = $db->getAll('hist', "bxiu_id = {$id}", '*', 'create_time DESC');
?>

<div class="page-header">
    <h2 class="page-title">报修详情</h2>
    <div class="page-tools">
        <a href="?do=libx" class="btn btn-primary">返回列表</a>
    </div>
</div>

<div class="card mb-4">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <h3><?php echo htmlspecialchars($repair['title']); ?></h3>
            <span class="badge status-<?php echo strtolower($repair['status']); ?>"><?php echo $repair['status']; ?></span>
        </div>
    </div>
    <div class="card-body">
        <table class="info-table">
            <tbody>
                <tr>
                    <th>报修位置</th>
                    <td><?php echo htmlspecialchars($repair['location']); ?></td>
                </tr>
                <tr>
                    <th>提交人</th>
                    <td><?php echo htmlspecialchars($submitter['realname']); ?> (<?php echo htmlspecialchars($submitter['xuehao']); ?>)</td>
                </tr>
                <tr>
                    <th>联系电话</th>
                    <td><?php echo htmlspecialchars($submitter['phone']); ?></td>
                </tr>
                <tr>
                    <th>提交时间</th>
                    <td><?php echo format_date($repair['create_time']); ?></td>
                </tr>
                <tr>
                    <th>最后更新</th>
                    <td><?php echo format_date($repair['update_time']); ?></td>
                </tr>
                <tr>
                    <th>问题描述</th>
                    <td><?php echo nl2br(htmlspecialchars($repair['description'])); ?></td>
                </tr>
                <?php if (!empty($repair['images'])): ?>
                <tr>
                    <th>图片附件</th>
                    <td>
                        <div class="image-gallery mt-2">
                            <?php 
                            $images = json_decode($repair['images'], true);
                            foreach ($images as $image): 
                            ?>
                            <div class="image-item">
                                <a href="<?php echo $image; ?>" target="_blank">
                                    <img src="<?php echo $image; ?>" alt="报修图片">
                                </a>
                                <span class="image-delete" onclick="deleteImage('<?php echo $image; ?>', 'bxiu', <?php echo $repair['id']; ?>)">删除</span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- 沟通记录 -->
<div class="card mb-4">
    <div class="card-header">
        <h3 class="card-title">沟通记录</h3>
    </div>
    <div class="card-body">
        <?php if (empty($history)): ?>
        <div class="text-center">
            <p>暂无沟通记录</p>
        </div>
        <?php else: ?>
        <div class="timeline">
            <?php 
            foreach ($history as $item): 
                $user_name = get_user_name($item['user_id'], $mysqli);
                $is_self = $item['user_id'] == $_SESSION['user_id'];
            ?>
            <div class="timeline-item <?php echo $is_self ? 'timeline-self' : ''; ?>">
                <div class="timeline-header">
                    <span class="timeline-user"><?php echo htmlspecialchars($user_name); ?></span>
                    <span class="timeline-time"><?php echo format_date($item['create_time']); ?></span>
                </div>
                <div class="timeline-content">
                    <?php if (!empty($item['content'])): ?>
                    <div class="timeline-text">
                        <?php echo nl2br(htmlspecialchars($item['content'])); ?>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($item['images'])): ?>
                    <div class="image-gallery">
                        <?php 
                        $images = json_decode($item['images'], true);
                        foreach ($images as $image): 
                        ?>
                        <div class="image-item">
                            <a href="<?php echo $image; ?>" target="_blank">
                                <img src="<?php echo $image; ?>" alt="沟通图片">
                            </a>
                            <span class="image-delete" onclick="deleteImage('<?php echo $image; ?>', 'hist', <?php echo $item['id']; ?>)">删除</span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 处理表单 -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">处理报修</h3>
    </div>
    <div class="card-body">
        <form id="replyForm">
            <table class="info-table">
                <tbody>
                    <tr>
                        <th><label for="content">回复内容</label></th>
                        <td><textarea class="form-control" id="content" name="content" rows="4" placeholder="请输入处理结果或回复内容"></textarea></td>
                    </tr>
                    <tr>
                        <th><label for="status">修改状态</label></th>
                        <td>
                            <select class="form-control" id="status" name="status">
                                <option value="未处理" <?php echo $repair['status'] == '未处理' ? 'selected' : ''; ?>>未处理</option>
                                <option value="处理中" <?php echo $repair['status'] == '处理中' ? 'selected' : ''; ?>>处理中</option>
                                <option value="已完成" <?php echo $repair['status'] == '已完成' ? 'selected' : ''; ?>>已完成</option>
                                <option value="已关闭" <?php echo $repair['status'] == '已关闭' ? 'selected' : ''; ?>>已关闭</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label>上传图片</label></th>
                        <td>
                            <input type="file" class="form-control" id="imageUpload" accept="image/*" multiple>
                            <small class="form-text text-muted">支持jpg、png、gif格式，最多5张，单张图片不超过<?php echo MAX_UPLOAD_SIZE; ?>MB</small>
                            <div id="imagePreview" class="image-preview mt-2"></div>
                            <input type="hidden" id="images_json" name="images_json">
                        </td>
                    </tr>
                    <tr>
                        <th></th>
                        <td><button type="button" class="btn btn-primary" id="submitBtn">提交处理</button></td>
                    </tr>
                </tbody>
            </table>
        </form>
    </div>
</div>

<style>
.image-gallery {
    display: flex;
    flex-wrap: wrap;
    margin: 10px 0;
}

.image-gallery .image-item {
    width: 120px;
    height: 120px;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
}

.image-gallery .image-item img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-gallery .image-item .image-delete {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    text-align: center;
    padding: 4px;
    font-size: 12px;
    cursor: pointer;
    display: none;
}

.image-gallery .image-item:hover .image-delete {
    display: block;
}

.timeline {
    position: relative;
    padding: 20px 0;
}

.timeline-item {
    margin-bottom: 20px;
    position: relative;
    padding-left: 20px;
    border-left: 2px solid #e0e0e0;
}

.timeline-self {
    border-left: 2px solid #bbdefb;
    background-color: #f5f9fd;
}

.timeline-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.timeline-user {
    font-weight: bold;
    color: #3f51b5;
}

.timeline-time {
    color: #757575;
    font-size: 0.9em;
}

.timeline-content {
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
}

.timeline-text {
    margin-bottom: 10px;
}

.badge {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 30px;
    font-size: 0.8em;
}

.status-未处理 {
    background-color: #ffecb3;
    color: #ff8f00;
}

.status-处理中 {
    background-color: #bbdefb;
    color: #1976d2;
}

.status-已完成 {
    background-color: #c8e6c9;
    color: #388e3c;
}

.status-已关闭 {
    background-color: #e0e0e0;
    color: #757575;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 图片上传预览
    document.getElementById('imageUpload').addEventListener('change', function() {
        var files = this.files;
        if (files.length > 5) {
            showToast('最多只能上传5张图片', 'warning');
        }
        
        previewImage(this, 'imagePreview', 5);
    });
    
    // 提交处理
    document.getElementById('submitBtn').addEventListener('click', function() {
        var content = document.getElementById('content').value;
        var status = document.getElementById('status').value;
        var imageUpload = document.getElementById('imageUpload');
        
        // 简单验证
        if (!content && (!imageUpload.fileArray || imageUpload.fileArray.length === 0)) {
            showToast('请输入回复内容或上传图片', 'warning');
            return;
        }
        
        // 按钮状态
        var submitBtn = this;
        submitBtn.disabled = true;
        submitBtn.textContent = '处理中...';
        
        // 如果有图片，先上传图片
        if (imageUpload.fileArray && imageUpload.fileArray.length > 0) {
            uploadImages(imageUpload, function(uploaded) {
                // 处理上传结果
                if (uploaded.length > 0) {
                    document.getElementById('images_json').value = JSON.stringify(uploaded);
                }
                
                // 提交表单数据
                submitFormData();
                
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.textContent = '提交处理';
            });
        } else {
            // 直接提交表单数据
            submitFormData();
            
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.textContent = '提交处理';
        }
    });
    
    // 提交表单数据
    function submitFormData() {
        var formData = getFormData('replyForm');
        
        ajax('?do=repa&id=<?php echo $id; ?>&act=reply', formData, function(response) {
            if (response.status === 'success') {
                showToast(response.msg, 'success');
                
                // 清空表单
                document.getElementById('replyForm').reset();
                document.getElementById('imagePreview').innerHTML = '';
                
                // 2秒后刷新页面
                setTimeout(function() {
                    window.location.reload();
                }, 2000);
            } else {
                showToast(response.msg, 'error');
            }
        });
    }
    
    // 图片点击放大
    var imageGalleries = document.querySelectorAll('.image-gallery');
    imageGalleries.forEach(function(gallery) {
        var images = gallery.querySelectorAll('img');
        var imageSrcs = [];
        
        // 收集当前图片组的所有图片路径
        images.forEach(function(img) {
            imageSrcs.push(img.src);
        });
        
        // 给每个图片添加点击事件
        images.forEach(function(img, index) {
            img.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                showImageGallery(imageSrcs, index);
            });
        });
    });
    
    // 显示带导航的图片库
    function showImageGallery(images, startIndex) {
        var currentIndex = startIndex;
        
        // 创建模态框
        var modal = document.createElement('div');
        modal.className = 'image-modal';
        modal.style.position = 'fixed';
        modal.style.top = '0';
        modal.style.left = '0';
        modal.style.width = '100%';
        modal.style.height = '100%';
        modal.style.backgroundColor = 'transparent';
        modal.style.display = 'flex';
        modal.style.justifyContent = 'center';
        modal.style.alignItems = 'center';
        modal.style.zIndex = '2000';
        modal.style.pointerEvents = 'none';
        
        // 创建模态框内容容器
        var modalContent = document.createElement('div');
        modalContent.className = 'modal-content';
        modalContent.style.position = 'relative';
        modalContent.style.pointerEvents = 'auto';
        
        // 创建图片容器
        var imgContainer = document.createElement('div');
        imgContainer.style.position = 'relative';
        imgContainer.style.width = '80%';
        imgContainer.style.height = '80%';
        imgContainer.style.display = 'flex';
        imgContainer.style.justifyContent = 'center';
        imgContainer.style.alignItems = 'center';
        imgContainer.style.margin = '0 auto';
        
        // 创建图片元素
        var img = document.createElement('img');
        img.src = images[currentIndex];
        img.style.maxWidth = '100%';
        img.style.maxHeight = '100%';
        img.style.objectFit = 'contain';
        
        // 创建关闭按钮
        var closeBtn = document.createElement('div');
        closeBtn.innerHTML = '&times;';
        closeBtn.style.position = 'absolute';
        closeBtn.style.top = '20px';
        closeBtn.style.right = '30px';
        closeBtn.style.color = 'white';
        closeBtn.style.fontSize = '35px';
        closeBtn.style.fontWeight = 'bold';
        closeBtn.style.cursor = 'pointer';
        closeBtn.style.zIndex = '2001';
        closeBtn.addEventListener('click', function() {
            document.body.removeChild(modal);
        });
        
        // 创建导航按钮容器
        var navContainer = document.createElement('div');
        navContainer.style.position = 'absolute';
        navContainer.style.bottom = '20px';
        navContainer.style.left = '0';
        navContainer.style.right = '0';
        navContainer.style.textAlign = 'center';
        
        // 创建上一张按钮
        var prevBtn = document.createElement('button');
        prevBtn.textContent = '上一张';
        prevBtn.className = 'btn btn-light btn-sm mx-2';
        prevBtn.style.marginRight = '10px';
        prevBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            currentIndex = (currentIndex - 1 + images.length) % images.length;
            img.src = images[currentIndex];
            updateCounter();
        });
        
        // 创建计数器
        var counter = document.createElement('span');
        counter.style.color = 'white';
        counter.style.margin = '0 10px';
        
        // 创建下一张按钮
        var nextBtn = document.createElement('button');
        nextBtn.textContent = '下一张';
        nextBtn.className = 'btn btn-light btn-sm mx-2';
        nextBtn.style.marginLeft = '10px';
        nextBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            currentIndex = (currentIndex + 1) % images.length;
            img.src = images[currentIndex];
            updateCounter();
        });
        
        // 更新计数器显示
        function updateCounter() {
            counter.textContent = (currentIndex + 1) + ' / ' + images.length;
        }
        
        // 初始化计数器
        updateCounter();
        
        // 添加元素到DOM
        navContainer.appendChild(prevBtn);
        navContainer.appendChild(counter);
        navContainer.appendChild(nextBtn);
        
        imgContainer.appendChild(img);
        
        modalContent.appendChild(imgContainer);
        modalContent.appendChild(closeBtn);
        modalContent.appendChild(navContainer);
        
        modal.appendChild(modalContent);
        
        document.body.appendChild(modal);
        
        // 添加键盘导航
        document.addEventListener('keydown', keyHandler);
        
        // 点击模态框关闭
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                document.body.removeChild(modal);
                document.removeEventListener('keydown', keyHandler);
            }
        });
        
        // 键盘事件处理
        function keyHandler(e) {
            if (e.key === 'ArrowLeft') {
                // 左箭头，显示上一张
                currentIndex = (currentIndex - 1 + images.length) % images.length;
                img.src = images[currentIndex];
                updateCounter();
            } else if (e.key === 'ArrowRight') {
                // 右箭头，显示下一张
                currentIndex = (currentIndex + 1) % images.length;
                img.src = images[currentIndex];
                updateCounter();
            } else if (e.key === 'Escape') {
                // ESC键关闭模态框
                document.body.removeChild(modal);
                document.removeEventListener('keydown', keyHandler);
            }
        }
    }
});

// 删除图片
function deleteImage(path, type, id) {
    if (!confirm('确定要删除这张图片吗？此操作不可恢复！')) {
        return;
    }
    
    ajax('?do=repa&id=<?php echo $id; ?>&act=delete_image', {
        path: path,
        type: type,
        record_id: id
    }, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
            
            // 刷新页面
            setTimeout(function() {
                window.location.reload();
            }, 1500);
        } else {
            showToast(response.msg, 'error');
        }
    });
}
</script>
